package top.suven.base.http.Interceptor;

import top.suven.base.http.NetworkUtil;
import top.suven.base.http.message.ParamMessage;
import top.suven.base.http.message.RequestMessage;
import top.suven.base.http.message.RequestRemote;
import top.suven.base.util.utilize.JsonUtils;
import top.suven.base.util.utilize.SignParam;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class JsonHandlerInterceptorAdapter extends HandlerInterceptorAdapter {
    //AbstractHandlerMethodAdapter  HandlerInterceptorAdapter

    private Logger logger = LoggerFactory.getLogger(getClass());

    @SuppressWarnings("unchecked")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是get还是post
        boolean isPostReq = request.getMethod().equals(RequestMethod.POST.name());
        request.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE,Sets.newHashSet(MediaType.APPLICATION_JSON));


        Map param = request.getParameterMap();
        if(null == param || (isPostReq && param.size() < 1)){
            logger.warn("[BAD PARAM] size < 1 or is null. url:{}", request.getRequestURI());
            throw new Exception("no request param, request url:"+request.getRequestURI());
        }
        //返回签名
        RequestMessage message = RequestMessage.parseFrom(param,RequestMessage.class);
        if(message == null)
            throw new Exception("request data error, request url : "+request.getRequestURI());
        long netTime = message.getTimes();
        long sysTime = System.currentTimeMillis();
        message.setIp(NetworkUtil.getIpAddress(request));
        message.setUri(request.getRequestURI());
        message.setTimes(sysTime);

        ParamMessage.setRequestMessage(message);

        RequestRemote remote = new RequestRemote();
        remote.setClientIp(message.getIp());
        String url = request.getServletPath();
        remote.setUrl(url);
        remote.setClientIp(message.getIp());
        remote.setSrvMd5Sign(SignParam.getServerSign(param));
        remote.setCliMd5Sign(message.getCliSign());
        remote.setPostReq(isPostReq);
        remote.setNetTime(sysTime - netTime);

        ParamMessage.setRequestRemote(remote);

        logger.info("receive client request url=[{}],mode=[{}] ,param=[{}] ",request.getRequestURI(),request.getMethod(), JsonUtils.map2String(param));

        return true;
    }


    /**
     * This implementation is empty.
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
        logger.debug("JsonHandlerInterceptorAdapter preHandle method ModelAndView 2 ...." );
    }

    /**
     * This implementation is empty.
     */
    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        logger.debug("JsonHandlerInterceptorAdapter afterCompletion method 3 ...." );
    }

    /**
     * This implementation is empty.
     */
    @Override
    public void afterConcurrentHandlingStarted(
            HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        logger.debug("JsonHandlerInterceptorAdapter afterConcurrentHandlingStarted method 4 ...." );
    }


}
